import React, { useEffect, useRef, useState, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { GameEngine } from '../utils/gameEngine';
import { AnimationSystem } from '../utils/animationSystem';
import { AudioManager } from '../utils/audioManager';
import { GameStateManager } from '../utils/gameState';
import { GameFruit, GameState, Position } from '../types/game';
import { GAME_CONFIG, canMerge, getMergedFruit } from '../config/fruits';
import { Play, Pause, RotateCcw, Volume2, VolumeX } from 'lucide-react';

export const WatermelonGame: React.FC = () => {
  const gameContainerRef = useRef<HTMLDivElement>(null);
  const gameEngineRef = useRef<GameEngine | null>(null);
  const animationSystemRef = useRef<AnimationSystem | null>(null);
  const audioManagerRef = useRef<AudioManager | null>(null);
  const gameStateManagerRef = useRef<GameStateManager | null>(null);
  
  const [gameState, setGameState] = useState<GameState | null>(null);
  const [dropPosition, setDropPosition] = useState<number>(GAME_CONFIG.CONTAINER_WIDTH / 2);
  const [canDrop, setCanDrop] = useState(true);
  const [showGameOver, setShowGameOver] = useState(false);
  const [isMuted, setIsMuted] = useState(false);
  const [gameInitialized, setGameInitialized] = useState(false);

  // 开始游戏（先显示游戏界面，再初始化引擎）
  const startGame = useCallback(() => {
    try {
      console.log('开始游戏...');
      
      // 先设置游戏已初始化，显示游戏界面
      setGameInitialized(true);
      
      // 创建游戏状态管理器并设置基本状态
      gameStateManagerRef.current = new GameStateManager();
      const unsubscribe = gameStateManagerRef.current.subscribe(setGameState);
      gameStateManagerRef.current.startGame();
      
      console.log('游戏界面已显示，等待初始化引擎...');
      
      // 延迟初始化物理引擎，确保DOM已经渲染
      setTimeout(() => {
        initializeGameEngine();
      }, 100);
      
    } catch (error) {
      console.error('开始游戏失败:', error);
    }
  }, []);

  // 初始化游戏引擎
  const initializeGameEngine = useCallback(() => {
    try {
      console.log('开始初始化游戏引擎...');
      
      if (!gameContainerRef.current) {
        console.error('游戏容器仍未找到，再次尝试...');
        // 再等待一下后重试
        setTimeout(() => {
          initializeGameEngine();
        }, 200);
        return;
      }

      console.log('游戏容器找到，开始初始化引擎...');

      // 清理现有系统
      cleanupGame();

      // 创建游戏引擎
      gameEngineRef.current = new GameEngine();
      gameEngineRef.current.initRender(gameContainerRef.current);
      console.log('游戏引擎创建成功');

      // 创建动画系统
      animationSystemRef.current = new AnimationSystem();
      const particleCanvas = animationSystemRef.current.getCanvas();
      if (particleCanvas) {
        gameContainerRef.current.appendChild(particleCanvas);
      }
      console.log('动画系统创建成功');

      // 创建音效管理器
      audioManagerRef.current = new AudioManager();
      console.log('音效管理器创建成功');

      // 设置游戏事件
      setupGameEvents();
      
      console.log('游戏引擎初始化完成');
      
    } catch (error) {
      console.error('游戏引擎初始化失败:', error);
    }
  }, []);

  // 设置游戏事件
  const setupGameEvents = () => {
    try {
      if (!gameEngineRef.current) {
        console.warn('游戏引擎未创建，跳过事件设置');
        return;
      }

      // 水果碰撞事件
      gameEngineRef.current.onFruitCollision = (fruit1: GameFruit, fruit2: GameFruit) => {
        if (canMerge(fruit1.type, fruit2.type)) {
          handleFruitMerge(fruit1, fruit2);
        }
      };

      // 游戏结束事件
      gameEngineRef.current.onGameOver = () => {
        handleGameOver();
      };
      
      console.log('游戏事件设置成功');
    } catch (error) {
      console.error('设置游戏事件失败:', error);
    }
  };

  // 处理水果合成
  const handleFruitMerge = (fruit1: GameFruit, fruit2: GameFruit) => {
    if (!gameEngineRef.current || !animationSystemRef.current || !audioManagerRef.current || !gameStateManagerRef.current) return;

    const mergedFruitType = getMergedFruit(fruit1.type);
    if (!mergedFruitType) return;

    // 计算合成位置（两个水果的中点）
    const mergePosition: Position = {
      x: (fruit1.body.position.x + fruit2.body.position.x) / 2,
      y: (fruit1.body.position.y + fruit2.body.position.y) / 2
    };

    // 移除原有水果
    gameEngineRef.current.removeFruit(fruit1);
    gameEngineRef.current.removeFruit(fruit2);

    // 创建新水果
    const newFruit = gameEngineRef.current.createFruit(mergedFruitType, mergePosition);

    // 创建合成特效
    animationSystemRef.current.createMergeEffect(
      mergePosition,
      mergedFruitType.color,
      mergedFruitType.radius
    );

    // 播放合成音效
    audioManagerRef.current.playMergeSound(mergedFruitType.id);

    // 增加分数
    const score = mergedFruitType.score;
    gameStateManagerRef.current.addScore(score);

    // 创建得分特效
    animationSystemRef.current.createScoreEffect(mergePosition, score);

    // 播放得分音效
    audioManagerRef.current.playScoreSound(score);
  };

  // 处理游戏结束
  const handleGameOver = () => {
    if (!animationSystemRef.current || !audioManagerRef.current || !gameStateManagerRef.current) return;

    gameStateManagerRef.current.gameOver();
    setShowGameOver(true);

    // 播放游戏结束特效
    animationSystemRef.current.createGameOverEffect();
    audioManagerRef.current.playGameOverSound();

    // 检查是否创造新纪录
    const stats = gameStateManagerRef.current.getScoreStats();
    if (stats.isNewRecord) {
      audioManagerRef.current.playHighScoreSound();
    }
  };

  // 投放水果
  const dropFruit = useCallback((x?: number) => {
    if (!gameEngineRef.current || !animationSystemRef.current || !audioManagerRef.current || !gameStateManagerRef.current) return;
    if (!canDrop || !gameState?.isPlaying) return;

    const position: Position = {
      x: x ?? dropPosition,
      y: 50
    };

    // 创建水果
    const fruit = gameEngineRef.current.createFruit(gameState.currentFruit, position);

    // 创建投放特效
    animationSystemRef.current.createDropEffect(position, gameState.currentFruit.color);

    // 播放投放音效
    audioManagerRef.current.playDropSound();

    // 更新游戏状态
    gameStateManagerRef.current.updateCurrentFruit();

    // 设置投放冷却
    setCanDrop(false);
    setTimeout(() => setCanDrop(true), GAME_CONFIG.DROP_COOLDOWN);
  }, [dropPosition, canDrop, gameState]);

  // 处理鼠标/触摸移动
  const handlePointerMove = (event: React.PointerEvent) => {
    if (!gameEngineRef.current || !gameState?.isPlaying) return;

    const position = gameEngineRef.current.getWorldPosition(event.clientX, event.clientY);
    if (position) {
      setDropPosition(position.x);
    }
  };

  // 处理点击投放
  const handleClick = (event: React.MouseEvent) => {
    if (!gameEngineRef.current) return;

    const position = gameEngineRef.current.getWorldPosition(event.clientX, event.clientY);
    if (position) {
      dropFruit(position.x);
    }
  };

  // 处理键盘事件
  const handleKeyPress = useCallback((event: KeyboardEvent) => {
    if (!gameState) return;

    switch (event.code) {
      case 'Space':
        event.preventDefault();
        if (gameState.isGameOver) {
          restartGame();
        } else {
          dropFruit();
        }
        break;
      case 'KeyP':
        event.preventDefault();
        togglePause();
        break;
      case 'KeyR':
        event.preventDefault();
        restartGame();
        break;
      case 'KeyM':
        event.preventDefault();
        toggleMute();
        break;
    }
  }, [gameState, dropFruit]);

  // 重新开始游戏
  const restartGame = () => {
    if (!gameStateManagerRef.current) return;

    setShowGameOver(false);
    gameEngineRef.current?.clearFruits();
    gameStateManagerRef.current.resetGame();
    
    if (audioManagerRef.current) {
      audioManagerRef.current.playButtonSound();
    }
  };

  // 暂停/恢复游戏
  const togglePause = () => {
    if (!gameStateManagerRef.current) return;
    
    gameStateManagerRef.current.togglePause();
    
    if (audioManagerRef.current) {
      audioManagerRef.current.playButtonSound();
    }
  };

  // 切换静音
  const toggleMute = () => {
    if (!audioManagerRef.current) return;
    
    audioManagerRef.current.toggleMute();
    setIsMuted(audioManagerRef.current.getMuted());
    audioManagerRef.current.playButtonSound();
  };

  // 清理游戏系统
  const cleanupGame = () => {
    gameEngineRef.current?.destroy();
    animationSystemRef.current?.destroy();
    audioManagerRef.current?.destroy();
    gameEngineRef.current = null;
    animationSystemRef.current = null;
    audioManagerRef.current = null;
  };

  // 组件卸载时清理
  useEffect(() => {
    return () => {
      cleanupGame();
    };
  }, []);

  // 监听键盘事件
  useEffect(() => {
    window.addEventListener('keydown', handleKeyPress);
    return () => window.removeEventListener('keydown', handleKeyPress);
  }, [handleKeyPress]);

  // 显示游戏开始界面
  if (!gameInitialized) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-pink-100 via-orange-100 to-yellow-100 flex items-center justify-center p-4">
        <div className="bg-white rounded-3xl p-8 shadow-2xl max-w-md w-full text-center">
          <div className="text-6xl mb-6">🍉</div>
          <h1 className="text-4xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-pink-500 to-orange-500 mb-4">
            合成大西瓜
          </h1>
          <p className="text-gray-600 mb-8">
            让我们合成最大的西瓜吧！
            <br />
            相同水果碰撞会合成更大的水果
          </p>
          <button
            onClick={startGame}
            className="w-full bg-gradient-to-r from-pink-500 to-orange-500 text-white font-bold py-4 px-8 rounded-2xl text-xl hover:shadow-lg transition-all duration-200 hover:scale-105"
          >
            开始游戏 🎮
          </button>
        </div>
      </div>
    );
  }

  // 如果游戏已初始化但状态未设置，显示加载
  if (!gameState) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-gradient-to-br from-pink-100 to-orange-100">
        <div className="text-xl font-bold text-gray-600">游戏启动中...</div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-pink-100 via-orange-100 to-yellow-100 p-4">
      <div className="max-w-md mx-auto">
        {/* 游戏标题 */}
        <motion.div
          initial={{ y: -50, opacity: 0 }}
          animate={{ y: 0, opacity: 1 }}
          className="text-center mb-6"
        >
          <h1 className="text-4xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-pink-500 to-orange-500 mb-2">
            合成大西瓜
          </h1>
          <p className="text-gray-600">让我们合成最大的西瓜吧！🍉</p>
        </motion.div>

        {/* 分数显示 */}
        <motion.div
          initial={{ scale: 0.9, opacity: 0 }}
          animate={{ scale: 1, opacity: 1 }}
          className="bg-white rounded-2xl shadow-lg p-4 mb-4"
        >
          <div className="flex justify-between items-center">
            <div className="text-center">
              <div className="text-2xl font-bold text-pink-500">{gameState.score}</div>
              <div className="text-sm text-gray-500">当前分数</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-bold text-orange-500">{gameState.highScore}</div>
              <div className="text-sm text-gray-500">最高分数</div>
            </div>
          </div>
        </motion.div>

        {/* 下一个水果预览 */}
        <motion.div
          initial={{ x: 50, opacity: 0 }}
          animate={{ x: 0, opacity: 1 }}
          className="bg-white rounded-2xl shadow-lg p-4 mb-4"
        >
          <div className="flex items-center justify-between">
            <span className="text-sm text-gray-500">下一个：</span>
            <div className="flex items-center space-x-2">
              <span className="text-2xl">{gameState.nextFruit.emoji}</span>
              <span className="text-sm font-medium text-gray-700">{gameState.nextFruit.name}</span>
            </div>
          </div>
        </motion.div>

        {/* 游戏容器 */}
        <div className="relative">

          {/* 当前水果预览 */}
          {gameState.isPlaying && canDrop && (
            <motion.div
              className="absolute z-30 pointer-events-none"
              style={{
                left: `${dropPosition}px`,
                top: '30px',
                transform: 'translateX(-50%)'
              }}
              animate={{
                y: [0, -5, 0],
              }}
              transition={{
                duration: 1,
                repeat: Infinity,
                ease: "easeInOut"
              }}
            >
              <div
                className="rounded-full flex items-center justify-center text-white font-bold shadow-lg"
                style={{
                  width: `${gameState.currentFruit.radius * 2}px`,
                  height: `${gameState.currentFruit.radius * 2}px`,
                  backgroundColor: gameState.currentFruit.color,
                  fontSize: `${gameState.currentFruit.radius}px`
                }}
              >
                {gameState.currentFruit.emoji}
              </div>
            </motion.div>
          )}

          {/* 游戏画布容器 */}
          <div
            ref={gameContainerRef}
            className="relative mx-auto cursor-pointer"
            style={{ 
              width: GAME_CONFIG.CONTAINER_WIDTH,
              height: GAME_CONFIG.CONTAINER_HEIGHT
            }}
            onPointerMove={handlePointerMove}
            onClick={handleClick}
          />

          {/* 暂停遮罩 */}
          <AnimatePresence>
            {!gameState.isPlaying && !gameState.isGameOver && (
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                className="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center z-40 rounded-2xl"
              >
                <div className="text-white text-2xl font-bold">游戏暂停</div>
              </motion.div>
            )}
          </AnimatePresence>
        </div>

        {/* 控制按钮 */}
        <motion.div
          initial={{ y: 50, opacity: 0 }}
          animate={{ y: 0, opacity: 1 }}
          className="flex justify-center space-x-4 mt-6"
        >
          <button
            onClick={togglePause}
            className="bg-white rounded-full p-3 shadow-lg hover:shadow-xl transition-all duration-200 hover:scale-105"
            disabled={gameState.isGameOver}
          >
            {gameState.isPlaying ? (
              <Pause className="w-6 h-6 text-orange-500" />
            ) : (
              <Play className="w-6 h-6 text-green-500" />
            )}
          </button>

          <button
            onClick={restartGame}
            className="bg-white rounded-full p-3 shadow-lg hover:shadow-xl transition-all duration-200 hover:scale-105"
          >
            <RotateCcw className="w-6 h-6 text-blue-500" />
          </button>

          <button
            onClick={toggleMute}
            className="bg-white rounded-full p-3 shadow-lg hover:shadow-xl transition-all duration-200 hover:scale-105"
          >
            {isMuted ? (
              <VolumeX className="w-6 h-6 text-red-500" />
            ) : (
              <Volume2 className="w-6 h-6 text-purple-500" />
            )}
          </button>
        </motion.div>

        {/* 游戏说明 */}
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.5 }}
          className="text-center mt-6 text-sm text-gray-500"
        >
          <p>点击或移动鼠标来投放水果</p>
          <p>相同水果碰撞会合成更大的水果</p>
          <p>快捷键：空格(投放/重开) P(暂停) R(重开) M(静音)</p>
        </motion.div>

        {/* 游戏结束对话框 */}
        <AnimatePresence>
          {showGameOver && (
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
            >
              <motion.div
                initial={{ scale: 0.7, opacity: 0 }}
                animate={{ scale: 1, opacity: 1 }}
                exit={{ scale: 0.7, opacity: 0 }}
                className="bg-white rounded-3xl p-8 mx-4 max-w-sm w-full shadow-2xl"
              >
                <div className="text-center">
                  <div className="text-6xl mb-4">😢</div>
                  <h2 className="text-2xl font-bold text-gray-800 mb-2">游戏结束</h2>
                  
                  <div className="space-y-2 mb-6">
                    <div className="flex justify-between">
                      <span className="text-gray-600">本次分数：</span>
                      <span className="font-bold text-pink-500">{gameState.score}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-600">最高分数：</span>
                      <span className="font-bold text-orange-500">{gameState.highScore}</span>
                    </div>
                  </div>

                  {gameState.score === gameState.highScore && gameState.score > 0 && (
                    <div className="bg-gradient-to-r from-pink-100 to-orange-100 rounded-lg p-3 mb-4">
                      <div className="text-lg">🎉 恭喜创造新纪录！</div>
                    </div>
                  )}

                  <button
                    onClick={restartGame}
                    className="w-full bg-gradient-to-r from-pink-500 to-orange-500 text-white font-bold py-3 px-6 rounded-2xl hover:shadow-lg transition-all duration-200 hover:scale-105"
                  >
                    再来一局
                  </button>
                </div>
              </motion.div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    </div>
  );
};